<?php
define('EXT_FUNC_DIR',dirname(__FILE__).'/extensions/');

if(!function_exists('file_put_contents')){
	define('FILE_APPEND', 1);
	function file_put_contents($n, $d, $flag = false) {
		$mode = ($flag == FILE_APPEND || strtoupper($flag) == 'FILE_APPEND') ? 'a' : 'w';
		$f = @fopen($n, $mode);
		if ($f === false) {
			return 0;
		} else {
			if (is_array($d)) $d = implode($d);
			$bytes_written = fwrite($f, $d);
			fclose($f);
			return $bytes_written;
		}
	}
}

if(!function_exists('str_ireplace')) {
	function str_ireplace($search, $replacement, $string){
		$delimiters = array(1,2,3,4,5,6,7,8,14,15,16,17,18,19,20,21,22,23,24,25,
			26,27,28,29,30,31,33,247,215,191,190,189,188,187,186,
			185,184,183,182,180,177,176,175,174,173,172,171,169,
			168,167,166,165,164,163,162,161,157,155,153,152,151,
			150,149,148,147,146,145,144,143,141,139,137,136,135,
			134,133,132,130,129,128,127,126,125,124,123,96,95,94,
			63,62,61,60,59,58,47,46,45,44,38,37,36,35,34);
		foreach ($delimiters as $d) {
			if (strpos($string, chr($d))===false){
				$delimiter = chr($d);
				break;
			}
		}
		if (!empty($delimiter)) {
			return preg_replace($delimiter.quotemeta($search).$delimiter.'i', $replacement, $string);
		}
		else {
			trigger_error('Homemade str_ireplace could not find a proper delimiter.', E_USER_ERROR);
		}
	}
}

function jsValue(&$value) {
	switch(gettype($value)) {
	case 'double':
	case 'integer':
		return $value>0?$value:'"'.$value.'"';
	case 'boolean':
		return $value?'true':'false';
	case 'string':
		return '"'.str_replace(
			array("\n","\b","\t","\f","\r"),
			array('\n','\b','\t','\f','\r'),
			addslashes($value)
		).'"';
	case 'NULL':
		return 'null';
	case 'object':
		return '"Object '.addslashes(get_class($value)).'"';
	case 'array':
		if (isVector($value)){
			foreach($value as $v){
				$result[] = jsValue($v);
			}
			return '['.implode(',',$result).']';
		}else {
			$result = '{';
			foreach ($value as $k=>$v) {
				if ($result != '{') $result .= ',';
				$result .= jsValue($k).':'.jsValue($v);
			}
			return $result.'}';
		}
	default:
		return '"'.addslashes($value).'"';
	}
}

function isVector (&$array) {
	$next = 0;
	foreach ($array as $k=>$v) {
		if ($k !== $next)
			return false;
		$next++;
	}
	return true;
}

if(!function_exists('json_encode')){
	define('EMU_JSON',true);
	function json_encode($value){
		return jsValue($value);
	}
}
//if(!function_exists('json_encode')){
//    function json_encode($value){
//        include_once(EXT_FUNC_DIR.'/json.php');
//        $json = new Services_JSON();
//        return $json->encode($value);
//    }
//}
if(!function_exists('json_decode')){
	function json_decode($json){
		include_once(EXT_FUNC_DIR.'/json.php');
		$json = new Services_JSON();
		return $json->decode($json);
	}
}

define('TIME_SHORT',0);
define('TIME_LANG',2);

function time_format($timestamp,$format = TIME_SHORT){
	switch($format){
	case TIME_SHORT:
		return date('n-j H:m',$timestamp);
	case TIME_LANG:
		return date('D M j',$timestamp);
	default:
		return date('Y-j-n',$timestamp);
	}
}

//将日期格式年-月-日转成时间戳
function dateToTimestamp($date=''){
	if($date == '') return time();
	$aDate = explode("-", $date);
	return mktime(0, 0, 0, $aDate[1], $aDate[2], $aDate[0]);
}

//取毫秒
function getMicrotime(){
	list($usec, $sec) = explode(" ",microtime());
	return ((float)$usec + (float)$sec);
}

function mkdir_p($dir,$dirmode=700){
	if (!empty($dir))
	{
		if (!file_exists($dir))
		{
			preg_match_all('/([^\/]*)\/?/i', $dir,$atmp);
			$base="";
			foreach ($atmp[0] as $key=>$val)
			{
				$base=$base.$val;
				if(!file_exists($base))
					if (!ftpMkdir($base,$dirmode))
					{
						echo "Error: Cannot create ".$base;
						return false;
					}
			}
		}
		else
			if (!is_dir($dir))
			{
				echo "Error: ".$dir." exists and is not a directory";
				return false;
			}
	}

	return true;
}

function copy_tree($source,$target){
	$dirhandle=@opendir($source);
	while($file_name=@readdir($dirhandle)){
        	if ($file_name!="." && $file_name!=".."){
			if (is_dir("$source/$file_name")){
				ftpMkdir("$target/$file_name",0777);
				copy_tree($source."/".$file_name,$target."/".$file_name);
			}else{
				copy("$source/$file_name","$target/$file_name");
				@chmod("$target/$file_name",0666);
			}
		}
	}
	@closedir($dirhandle);
}

function deltree($dir) {

	$dirhandle=@opendir($dir);
	while($file_name=@readdir($dirhandle)){
        	if ($file_name!="." && $file_name!=".."){
			if (is_dir("$dir/$file_name")){
				deltree($dir."/".$file_name);
				@rmdir("$dir/$file_name");
			}else{
				@unlink("$dir/$file_name");
			}
		}
	}
	@closedir($dirhandle);
}


function file_rename($source,$dest){
	@copy($source,$dest);
	@unlink($source);
	if(file_exists($dest)) return true;
	else return false;
}

function code2utf($num)
{
	if($num<128)return chr($num);
	if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
	if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
	if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
	return '';
}

function decode_jsescape($string){
	preg_match_all('/%u[0-9A-F]{4}/',$string,$u_codes);
	foreach($u_codes[0] as $code){
		$string=str_replace($code,code2utf(hexdec(substr($code,2,4))),$string);
	}
	return $string;
}


function forwarded_path(){
	$addrs = array();

	foreach( array_reverse( explode( ',',  $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) as $x_f )
	{
		$x_f = trim($x_f);

		if ( preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/', $x_f ) )
		{
			$addrs[] = $x_f;
		}
	}

	$addrs[] = $_SERVER['REMOTE_ADDR'];
	return $addrs;
}

function remote_addr($wan_only=false){

	$addrs = forwarded_path();

	if($wan_only){
		foreach($addrs as $k=>$addr){
			preg_match( "/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})/",$addr,$matchs);
			if($matchs[1]==10){
				unset($addrs[$k]);
			}elseif($matchs[1]==172 && $matchs[2]>15 && $matchs[2]<32){
				unset($addrs[$k]);
			}elseif($matchs[1]==192 && $matchs[2]==168){
				unset($addrs[$k]);
			}
		}
	}
	return array_shift($addrs);
}

if (!function_exists('http_build_query')) {
	function http_build_query($formdata, $numeric_prefix = null)
	{
		// If $formdata is an object, convert it to an array
		if (is_object($formdata)) {
			$formdata = get_object_vars($formdata);
		}

		// Check we have an array to work with
		if (!is_array($formdata)) {
			user_error('http_build_query() Parameter 1 expected to be Array or Object. Incorrect value given.',
				E_USER_WARNING);
			return false;
		}

		// If the array is empty, return null
		if (empty($formdata)) {
			return;
		}

		// Argument seperator
		$separator = ini_get('arg_separator.output');

		// Start building the query
		$tmp = array ();
		foreach ($formdata as $key => $val) {
			if (is_integer($key) && $numeric_prefix != null) {
				$key = $numeric_prefix . $key;
			}

			if (is_scalar($val)) {
				array_push($tmp, urlencode($key).'='.urlencode($val));
				continue;
			}

			// If the value is an array, recursively parse it
			if (is_array($val)) {
				array_push($tmp, __http_build_query($val, urlencode($key)));
				continue;
			}
		}

		return implode($separator, $tmp);
	}

	// Helper function
	function __http_build_query ($array, $name)
	{
		$tmp = array ();
		foreach ($array as $key => $value) {
			if (is_array($value)) {
				array_push($tmp, __http_build_query($value, sprintf('%s[%s]', $name, $key)));
			} elseif (is_scalar($value)) {
				array_push($tmp, sprintf('%s[%s]=%s', $name, urlencode($key), urlencode($value)));
			} elseif (is_object($value)) {
				array_push($tmp, __http_build_query(get_object_vars($value), sprintf('%s[%s]', $name, $key)));
			}
		}

		// Argument seperator
		$separator = ini_get('arg_separator.output');

		return implode($separator, $tmp);
	}
}

//wildsetup
function txtDecode($str) {
	$ret = array();
	$str = str_replace("\r","",$str);
	$linearr = explode("\n",$str);
	while(list($k,$v)=each($linearr)) {
		if(trim($v)!="") {
			$arr = explode(":",trim($v),2);
			if(count($arr)==2)
				if($arr[0]!=""&&trim($arr[1])!="") $ret[$arr[0]] = trim($arr[1]);
		}
	}
	return $ret;
}

function txtEncode($arr) {
	$str = "";
	if(is_array($arr)) {
		while(list($k,$v)=each($arr)) {
			$str .= $k.":".trim($v)."\r\n";
		}
		return trim($str);
	}
	else return "";
}

function utf2local($string,$encoding) {
	if(!isset($uencodingtable[$encoding])) {
		$filename= dirname(__FILE__)."/../../../syssite/smtpmail/".$encoding.".txt" ;
		if(!file_exists($filename)||$filename=="") {
			return $string;
		}
		$fp = fopen($filename, "r");
		while ($buffer = fgetline($fp)) {
			$codetable[hexdec(substr($buffer,9,4))]=hexdec(substr($buffer,2,4));
		}
		fclose($fp);
		$uencodingtable[$encoding] = $codetable;
	} else {
		$codetable = $uencodingtable[$encoding];
	}
	$string=str_replace('+',' ',urlencode($string));
	$outstring="";
	$pre_str = "";
	$strarray = split("%",$string);
	if($strarray[0]!="") {
		$pre_str = $strarray[0];
	}
	for ($i=1;$i<count($strarray);$i++) {
		$asc_str = "";
		if(strlen($strarray[$i])>2) {
			$asc_str = substr($strarray[$i],2-strlen($strarray[$i]));
			$strarray[$i] = substr($strarray[$i],0,2);
		}

		if (hexdec($strarray[$i]) < 128) {
			if (hexdec($strarray[$i]))
				$outstring =$outstring . chr(hexdec($strarray[$i]));
		}
		if (hexdec($strarray[$i]) >= 224 and hexdec($strarray[$i]) < 239) {
			$charb1 = strval(decbin(hexdec($strarray[$i])) - 11100000);
			$charb1 = str_pad($charb1,4,"0",STR_PAD_LEFT);
			$i++;
			$asc_str = "";
			if(strlen($strarray[$i])>2) {
				$asc_str = substr($strarray[$i],2-strlen($strarray[$i]));
				$strarray[$i] = substr($strarray[$i],0,2);
			}
			$charb2 = strval(decbin(hexdec($strarray[$i])) - 10000000);
			$charb2 = str_pad($charb2,6,"0",STR_PAD_LEFT);
			$i++;
			$asc_str = "";
			if(strlen($strarray[$i])>2) {
				$asc_str = substr($strarray[$i],2-strlen($strarray[$i]));
				$strarray[$i] = substr($strarray[$i],0,2);
			}
			$charb3 = strval(decbin(hexdec($strarray[$i])) - 10000000);
			$charb3 = str_pad($charb3,6,"0",STR_PAD_LEFT);
			$pad1 = str_pad($charb1,10,$charb2);
			$outbin = str_pad($pad1,16,$charb3);
			//          $outsub = "&#".bindec($outbin).";";

			$p_out = decbin($codetable[bindec($outbin)]);
			$outsub = chr(bindec(substr($p_out,0,strlen($p_out)-8))).chr(bindec(substr($p_out,-8)));
			$outstring = $outstring . $outsub;
		}
		$outstring = $outstring . $asc_str;
	}
	return trim($pre_str).trim($outstring);
}

//读文件时取不定长的行

function fgetline($handle)
{
	$buffer = fgets($handle, 4096);
	if (!$buffer)
	{
		return false;
	}

	if(( 4095 > strlen($buffer)) || ( 4095 == strlen($buffer) && '\n' == $buffer{4094} ))
	{
		$line = $buffer;
	}
	else
	{
		$line = $buffer;
		while( 4095 == strlen($buffer) && '\n' != $buffer{4094} )
		{
			$buffer = fgets($handle,4096);
			$line.=$buffer;
		}
	}
	return $line;
}

//ext_valid($filename,$type)  检查上传源文件名是否合法
function ext_valid($filename,$type)
{
	$extarr = array();
	$filename = strtolower($filename);
	$extarr[0]= array(".gif",".jpg",".jpeg",".png");
	if(!isset($extarr[$type])) return false;
	if($ext = strrchr($filename,"."))
	{
		if(in_array($ext,$extarr[$type]))
		{
			return true;
		}else return false;
	}
	else return false;
}

function dec2b36($int)
{
	$b36 = array(0=>"0",1=>"1",2=>"2",3=>"3",4=>"4",5=>"5",6=>"6",7=>"7",8=>"8",9=>"9",10=>"A",11=>"B",12=>"C",13=>"D",14=>"E",15=>"F",16=>"G",17=>"H",18=>"I",19=>"J",20=>"K",21=>"L",22=>"M",23=>"N",24=>"O",25=>"P",26=>"Q",27=>"R",28=>"S",29=>"T",30=>"U",31=>"V",32=>"W",33=>"X",34=>"Y",35=>"Z");
	$retstr = "";
	if($int>0)
	{
		while($int>0)
		{
			$retstr = $b36[($int % 36)].$retstr;
			$int = floor($int/36);
		}
	}
	else
	{
		$retstr = "0";
	}

	return $retstr;
}

function local_emu(){
}

function T_setlocale($category, $locale) {
	global $CURRENT_LOCALE, $EMU_GETTEXT;
	$CURRENT_LOCALE = $locale;
	$EMU_GETTEXT = 1;
	return $CURRENT_LOCALE;

	if ($locale === 0) { // use === to differentiate between string "0"
		if ($CURRENT_LOCALE != '')
			return $CURRENT_LOCALE;
		else
			return $locale;
//      return T_setlocale($category, $CURRENT_LOCALE);
	} else {
/*
		$ret = 0;
		if (function_exists('setlocale'))
			$ret = setlocale($category, $locale.'.UTF-8') && putenv('LANG='.$locale);

		if (function_exists('gettext') && (($ret and $locale == '') or ($ret == $locale.'.UTF-8'))) {
			$EMU_GETTEXT = 0;
			$CURRENT_LOCALE = $ret;
		} else {
			if ($locale == '')
				$CURRENT_LOCALE = getenv('LANG');
			else
				$CURRENT_LOCALE = $locale;
			$EMU_GETTEXT = 1;
		}
*/
		$CURRENT_LOCALE = $locale;
		$EMU_GETTEXT = 1;
		return $CURRENT_LOCALE;
	}
}

function __($msgid) {
	global $CURRENT_LOCALE, $EMU_GETTEXT,$CURRENT_DOMAIN;
	$GLOBALS['EMU_GETTEXT'] = 1; //部分用户的php5.1.2版本的这里无值，这里强制赋值了
	if($GLOBALS['EMU_GETTEXT']){
		return $GLOBALS['__lang'][$CURRENT_LOCALE][$CURRENT_DOMAIN][$msgid]?$GLOBALS['__lang'][$CURRENT_LOCALE][$CURRENT_DOMAIN][$msgid]:$msgid;
	}else
		return $GLOBALS['__lang'][$CURRENT_LOCALE][$CURRENT_DOMAIN][$msgid]?$GLOBALS['__lang'][$CURRENT_LOCALE][$CURRENT_DOMAIN][$msgid]:$msgid;
//		return _($msgid);
}

function loadMo($path) {
	if(!$handle = fopen($path, 'rb')) {
		return FALSE;
	}
	$magic = array_shift(unpack('V', fread($handle, 4)));
	if($magic == (int)0x0950412de)
		$order = 'V';
	elseif($magic == (int)0x0de120495)
		$order = 'N';
	else {
		$order = 'V';
		//return FALSE;
	}
	$revision = array_shift(unpack($order, fread($handle, 4)));
	$number_of_strings = array_shift(unpack($order, fread($handle, 4)));
	$original_table_offset = array_shift(unpack($order, fread($handle, 4)));
	$translated_table_offset = array_shift(unpack($order, fread($handle, 4)));
	$count = $number_of_strings * 2;
	fseek($handle, $original_table_offset);
	$original_table = unpack($order.$count, fread($handle, ($count * 4)));
	fseek($handle, $translated_table_offset);
	$translated_table = unpack($order.$count, fread($handle, ($count * 4)));
	$table=array();
	for($index = 0; $index < $number_of_strings; $index++) {
		fseek($handle, $original_table[$index * 2 + 2]);
		if(!$length = $original_table[$index * 2 + 1])
			$original = '';
		else
			$original = fread($handle, $length);
		fseek($handle, $translated_table[$index * 2 + 2]);
		if(!$length = $translated_table[$index * 2 + 1])
			$translated = '';
		else
			$translated = fread($handle, $length);
		$l10n[$language][$original] = $translated;
		$original = str_replace('\000', "'.chr(0).'", addcslashes($original, "\0\\'"));
		$translated = str_replace('\000', "'.chr(0).'", addcslashes($translated, "\0\\'"));
		if($original) $table[$original] = $translated;
	}
	return $table;
}
//}else{
//  define('EMU_GETTEXT',false);
//}

function echox() {
	if (defined('SHOP_DEVELOPER')&&SHOP_DEVELOPER) {
		$numargs = func_num_args();
		if ($numargs==0) return;
		$arg_list = func_get_args();
		for ($i = 0; $i < $numargs; $i++) {
			$v = $arg_list[$i];
			switch (gettype($v)) {
				case 'array' :
					echo '<pre>';
					print_r($v);
					echo '<pre>';
					break;
				case 'object':
					echo '<pre>';
					var_dump($v);
					echo '</pre>';
					break;
				case 'boolean ' :
					var_dump($v);
					break;
				case 'resource':
					echo $v;
					break;
				case 'string' :
				case 'integer' :
				case 'float' :
				case 'double':
				case 'string':
				default:
					print_r($v);
					break;

			}
			echo '<br>';
		}
	}
}

function remove_dots($str){
	global $real_path;
	$path_arr = explode("/",$str);
	$num = count($path_arr)-1;
	for($i=0;$i<$num;$i++){
		$j = $k = 0;
		if($path_arr[$i] == '.') $path_arr[$i]='';
		if($path_arr[$i] == ".."){
			$tmp = $k = $i;
			if($path_arr[$k+1] != '..' && !empty($path_arr[$k])){
				unset($path_arr[$k-1]);
			}else{
				while($path_arr[$k] == '..'){
					$j++;
					$k++;
				}
			}
			for($t=1;$t<=$j;$t++){
				unset($path_arr[$tmp]);
				unset($path_arr[$tmp-$j]);
				$tmp--;
			}
			if($j == 0)	unset($path_arr[$i]);
		}
	}
	return $real_path = implode("/",$path_arr);
}

function dealFTPDir(&$dir){
	$arr = explode('/', $dir);
	foreach($arr as $k=>$v){
		if($v != 'syssite'){
			unset($arr[$k]);
		}else{
			break;
		}
	}
	$dir = implode('/',$arr);
}

if (!function_exists('ftp_chmod')){
   function ftp_chmod($ftp_stream, $mode, $filename){
       return ftp_site($ftp_stream, sprintf('CHMOD %o %s', $mode, $filename));
   }
}

if(function_exists("ftp_connect")){
	//To connect the FTP Server
	function ftpConnect(){
		global $_FTP_CONNECTION;
		//Try to connect
		if(is_resource($_FTP_CONNECTION))return $_FTP_CONNECTION;
		else{
			$_FTP_CONNECTION = @ftp_connect(FTP_SERVER,FTP_PORT);
			if(!is_resource($_FTP_CONNECTION)) die('Error: FTP connect failed');
		}
		//Try to login
		if(!@ftp_login($_FTP_CONNECTION, FTP_USER, FTP_PASS)){
			die("Couldn't connect as ".FTP_USER."\n");
		}
		else return $_FTP_CONNECTION;
	}

	function ftpMkdir($dir,$mode){
		global $_FTP_CONNECTION;
		//Try to connect
		if(defined("FTP_ROOT")){
			$script_path = substr($_SERVER["PHP_SELF"],0,strrpos($_SERVER["PHP_SELF"],'/')+1);
			dealFTPDir($script_path);
			$dir = FTP_ROOT.'/'.$script_path.$dir;
			$dir = remove_dots($dir);
			if(!is_resource($_FTP_CONNECTION)) $_FTP_CONNECTION = ftpConnect();
			ftp_chdir($_FTP_CONNECTION,substr($dir,0,strrpos($dir,'/')));
			$ret = ftp_mkdir($_FTP_CONNECTION,$dir);
			ftp_chmod($_FTP_CONNECTION,$mode,$dir);
			return $ret;
		}
		else return mkdir($dir,$mode);
	}

	function ftpClose(){
		if(is_resource($_FTP_CONNECTION)) ftp_close($_FTP_CONNECTION);
	}

}else{

	require_once(BASE_DIR."/include/phpFtp.php");
	$FTP_CONNECT = 0;
	$phpFtp = '';
	function ftpConnect(){
		global $phpFtp,$FTP_CONNECT;
		$phpFtp = new phpFtp();
		if($FTP_CONNECT) return ;
		else{
			$phpFtp->connect(FTP_SERVER,FTP_PORT);
			if(!$phpFtp->isConnected()) die('Error: FTP connect failed');
		}
		if(!$phpFtp->login(FTP_USER, FTP_PASS)){
			die("Couldn't connect as ".FTP_USER."\n");
		}
		$FTP_CONNECT = 1;
		return $FTP_CONNECT;
	}

	function ftpMkdir($dir,$mode){
		global $phpFtp,$FTP_CONNECT;
		if(defined("FTP_ROOT")){
			$script_path = substr($_SERVER["PHP_SELF"],0,strrpos($_SERVER["PHP_SELF"],'/')+1);
			dealFTPDir($script_path);
			$dir = FTP_ROOT.'/'.$script_path.$dir;
			$dir = remove_dots($dir);
			if(!$FTP_CONNECT) ftpConnect();
			$phpFtp->chdir(substr($dir,0,strrpos($dir,'/')));
			$ret = $phpFtp->mkdir($dir);
			$mode = DecOct($mode);
			$phpFtp->chmod($mode,$dir);
			return $ret;
		}
		else return mkdir($dir,$mode);
	}

	function ftpClose(){
		global $phpFtp,$FTP_CONNECT;
		if($FTP_CONNECT ==1){
			$phpFtp->disconnect();
			$FTP_CONNECT = 0;
		}
	}

}
function temp_nam(){
	list($usec, $sec) = explode(' ', microtime());
	$seed = (float) $sec + ((float) $usec * 100000);
	srand($seed);
	return md5(time().rand());
}
/* 时区偏移计算
function userTime($nTimestamp) {
	return $nTimestamp += TIME_ZONE*3600 - SERVER_TIME_ZONE*3600;
}
function userDate($sFormat, $nTimestamp=NULL) {
	if ($nTimestamp == NULL) {
		$nTimestamp = time();
	}
	return date($sFormat, userTime($nTimestamp));
}

function serverTime($nTimestamp) {
	return $nTimestamp += SERVER_TIME_ZONE*3600 - TIME_ZONE*3600;
}
function serverDate($sFormat, $nTimestamp=NULL) {
	if ($nTimestamp == NULL) {
		$nTimestamp = time();
	}
	return date($sFormat, serverTime($nTimestamp));
}
*/

function make_seoname($str)
{
	$str = strip_tags($str);
	$str = str_replace(" ","-",$str);
	$str = str_replace("'","",$str);
	$str = str_replace("\"","",$str);
	$str = str_replace("/","_",$str);
	$str = str_replace("\\","_",$str);
	$str = str_replace(",","-",$str);
	$str = str_replace(".","-",$str);
	$str = str_replace("#","-",$str);
	$str = str_replace("<","",$str);
	$str = str_replace(">","",$str);
	$str = str_replace("|","",$str);
	$str = str_replace("?","",$str);
	$str = str_replace("&amp;","-",$str);
	$str = str_replace("&","-",$str);
	return $str;
}

//alone add start

  /**
	* alone 加密函数
	*
	* @param		string		等待加密的原字串
	* @param		string		私有密匙(用于解密和加密)
	*
	* @return	string		原字串经过私有密匙加密后的结果
	*/
	function passport_encrypt($txt, $key) {

		// 使用随机数发生器产生 0~32000 的值并 MD5()
		srand((double)microtime() * 1000000);
		$encrypt_key = md5(rand(0, 32000));

		// 变量初始化
		$ctr = 0;
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for($i = 0; $i < strlen($txt); $i++) {
			// 如果 $ctr = $encrypt_key 的长度，则 $ctr 清零
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			// $tmp 字串在末尾增加两位，其第一位内容为 $encrypt_key 的第 $ctr 位，
			// 第二位内容为 $txt 的第 $i 位与 $encrypt_key 的 $ctr 位取异或。然后 $ctr = $ctr + 1
			$tmp .= $encrypt_key[$ctr].($txt[$i] ^ $encrypt_key[$ctr++]);
		}
		// 返回结果，结果为 passport_key() 函数返回值的 base64 编码结果
		return base64_encode(passport_key($tmp, $key));

	}

  /**
	* alone 解密函数
	*
	* @param		string		加密后的字串
	* @param		string		私有密匙(用于解密和加密)
	*
	* @return	string		字串经过私有密匙解密后的结果
	*/
	function passport_decrypt($txt, $key) {

		// $txt 的结果为加密后的字串经过 base64 解码，然后与私有密匙一起，
		// 经过 passport_key() 函数处理后的返回值
		$txt = passport_key(base64_decode($txt), $key);

		// 变量初始化
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for ($i = 0; $i < strlen($txt); $i++) {
			// $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
			// 与 $txt 的第 $i + 1 位取异或。然后 $i = $i + 1
			$tmp .= $txt[$i] ^ $txt[++$i];
		}
		// 返回 $tmp 的值作为结果
		return $tmp;

	}

  /**
	* alone 密匙处理函数
	*
	* @param		string		待加密或待解密的字串
	* @param		string		私有密匙(用于解密和加密)
	*
	* @return	string		处理后的密匙
	*/
	function passport_key($txt, $encrypt_key) {

		// 将 $encrypt_key 赋为 $encrypt_key 经 md5() 后的值
		$encrypt_key = md5($encrypt_key);

		// 变量初始化
		$ctr = 0;
		$tmp = '';

		// for 循环，$i 为从 0 开始，到小于 $txt 字串长度的整数
		for($i = 0; $i < strlen($txt); $i++) {
			// 如果 $ctr = $encrypt_key 的长度，则 $ctr 清零
			$ctr = $ctr == strlen($encrypt_key) ? 0 : $ctr;
			// $tmp 字串在末尾增加一位，其内容为 $txt 的第 $i 位，
			// 与 $encrypt_key 的第 $ctr + 1 位取异或。然后 $ctr = $ctr + 1
			$tmp .= $txt[$i] ^ $encrypt_key[$ctr++];
		}

		// 返回 $tmp 的值作为结果
		return $tmp;
	}
//alone add end
?>
